using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DiskFactory : MonoBehaviour
{
    public GameObject diskPrefab; 
    private List<DiskData> used; 
    private List<DiskData> free; 

    public void Start()
    {
        diskPrefab = GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/f1"), Vector3.zero, Quaternion.identity);
        diskPrefab.SetActive(false);
        used = new List<DiskData>();
        free = new List<DiskData>();
    }

    public GameObject GetDisk(Ruler ruler)
    {
        GameObject disk;

        int diskNum = free.Count;
        if (diskNum == 0)
        {
            disk = GameObject.Instantiate(diskPrefab, Vector3.zero, Quaternion.identity);
            disk.AddComponent(typeof(DiskData));
        }
        else
        {
            disk = free[diskNum - 1].gameObject;
            free.Remove(free[diskNum - 1]);
        }

        disk.GetComponent<DiskData>().speed = ruler.speed;
        disk.GetComponent<DiskData>().color = ruler.color;
        disk.GetComponent<DiskData>().size = ruler.size;

        if (ruler.color == "red")
        {
            disk.GetComponent<Renderer>().material.color = Color.red;
        }
        else if (ruler.color == "green")
        {
            disk.GetComponent<Renderer>().material.color = Color.green;
        }
        else
        {
            disk.GetComponent<Renderer>().material.color = Color.blue;
        }

        disk.transform.localScale = new Vector3(1.2f, 0.1f * (float)ruler.size, 1.2f);

        disk.transform.position = ruler.beginPos;

        disk.SetActive(true);

        used.Add(disk.GetComponent<DiskData>());

        return disk;
    }

    public void FreeDisk(GameObject disk)
    {
        foreach (DiskData d in used)
        {
            if (d.gameObject.GetInstanceID() == disk.GetInstanceID())
            {
                disk.SetActive(false);
                used.Remove(d);
                free.Add(d);
                break;
            }

        }
    }
}
